from cryptography.fernet import Fernet, InvalidToken

from commonTool.logs.logs_wrapper import LogUtil

logs = LogUtil()


def generate_key():
    key = Fernet.generate_key()
    return key


def encrypt(_plaintext, _key):
    """
    加密
    :param _plaintext:   需要加密的明文 str
    :param _key:         密钥
    :return:            密文
    """
    f = Fernet(_key)
    _ciphertext = f.encrypt(_plaintext.encode("utf-8"))
    return _ciphertext.decode("utf-8")


@logs
def decrypt(_ciphertext, _key):
    """
    解密
    :param _ciphertext: 密文
    :param _key:        密钥
    :return:           明文
    """
    f = Fernet(_key)
    try:
        _plaintext = f.decrypt(_ciphertext.encode("utf-8"))
    except InvalidToken:
        logs.error("解密失败,请检查密文 和 密钥")
        _plaintext = b''
    return _plaintext.decode("utf-8")
